package com.digitalconsulting.shopaholic;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.digitalconsulting.datalayer.ItemList;
import com.digitalconsulting.datalayer.ItemListDataSource;
import com.digitalconsulting.datalayer.ItemListDataSource.Sort;

public class ShoppingListActivity extends ListActivity {
	
	ArrayList<ItemList> itemLists;
    String sort;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.shopping_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.sort_by_date:
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(),
					ShoppingListActivity.class);
			intent.putExtra("sort", "DATE");
			startActivity(intent);
			finish();
			return true;

		case R.id.sort_by_price:
			Intent intent2 = new Intent();
			intent2.setClass(getApplicationContext(),
					ShoppingListActivity.class);
			intent2.putExtra("sort", "PRICE");
			startActivity(intent2);
			finish();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		registerForContextMenu(getListView());

		ItemListDataSource dc = new ItemListDataSource(getApplicationContext());
		
		if (sort.contentEquals("NONE")) {
			itemLists = dc.getAll(Sort.NONE);
			
		}
		else if (sort.contentEquals("DATE"))
		{
			itemLists = dc.getAll(Sort.DATE);
		}
		else
		{
			itemLists = dc.getAll(Sort.PRICE);
		}
			
		
		

		setListAdapter(new ItemsAdapter(this, R.layout.list_item, itemLists));

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Dialog dialog = new Dialog(ShoppingListActivity.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.item_dialog);

				dialog.setCancelable(true);

				final ItemList o = itemLists.get(position);

				DecimalFormat df = new DecimalFormat("###,##0.00");

				/*final String txtPrice = df.format(o.getPrice());

				dialog.setTitle(txtPrice);*/

				Bitmap bitmap = BitmapFactory.decodeFile(o.getImagePath());

				ImageView img = (ImageView) dialog
						.findViewById(R.id.ImageView01);
				img.setImageBitmap(bitmap);

				final TextView txtPlace = (TextView) dialog.findViewById(R.id.txtPlace);
				txtPlace.setText(o.getPlace());

				final TextView txtPrice = (TextView) dialog.findViewById(R.id.txtPrice);
				txtPrice.setText(df.format(o.getPrice()));
				
				TextView txtDescription = (TextView) dialog
						.findViewById(R.id.txtDescription);
				txtDescription.setText(o.getDescription());

				Button btnLocate = (Button) dialog.findViewById(R.id.btnLocate);
				btnLocate.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						try {
							String longitude = o.getLongitude();
							String latitude = o.getLatitude();

							if (longitude == null) {
								AlertDialog.Builder builder = new AlertDialog.Builder(
										ShoppingListActivity.this)
										.setCancelable(false)
										.setMessage(
												"No saved location for this item!")
										.setNeutralButton(
												"Ok",
												new DialogInterface.OnClickListener() {

													public void onClick(
															DialogInterface dialog,
															int which) {
														dialog.cancel();

													}
												});
								builder.show();
							} else {
								Bundle bundle = new Bundle();
								bundle.putString("longitude", longitude);
								bundle.putString("latitude", latitude);

								Intent intent = new Intent();
								intent.putExtras(bundle);
								intent.setClass(getApplicationContext(),
										ShowOnMapActivity.class);
								startActivity(intent);
							}
						} catch (Exception e) {
							Log.d("Sasa", e.getMessage());
						}
					}
				});

				// btnDelete
				Button btnDelete = (Button) dialog.findViewById(R.id.btnDelete);
				btnDelete.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						
						AlertDialog.Builder dialog = new AlertDialog.Builder(ShoppingListActivity.this)
						           .setCancelable(false)
						           .setMessage("Are You sure?")
						           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
									
									public void onClick(DialogInterface dialog, int which) {
										ItemListDataSource dc = new ItemListDataSource(
												getApplicationContext());
										int id = o.getItemListId();

										dc.delete(id);

										startActivity(getIntent());
										finish();
										
									}
								})
								.setNegativeButton("No", new DialogInterface.OnClickListener() {
									
									public void onClick(DialogInterface dialog, int which) {
										dialog.cancel();
										
									}
								});
						dialog.show();
						
						
					}
				});

				// btnCancel
				Button btnCancel = (Button) dialog.findViewById(R.id.btnShare);
				btnCancel.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						Intent sharingIntent = new Intent(Intent.ACTION_SEND);
						sharingIntent.setType("text/plain");
						sharingIntent.putExtra(
								android.content.Intent.EXTRA_TEXT,
								String.format(
										"I've found this at the %1$s for %2$s!",
										o.getPlace(), txtPrice));
						sharingIntent.putExtra(Intent.EXTRA_SUBJECT,
								"Shopaholic");
						startActivity(Intent.createChooser(sharingIntent,
								"Share using"));

					}
				});

				dialog.show();
			}
		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Bundle b = getIntent().getExtras();
		sort = b.getString("sort");
		
	}

	private class ItemsAdapter extends ArrayAdapter<ItemList> {
		private ArrayList<ItemList> items;

		public ItemsAdapter(Context context, int textViewResourceId,
				ArrayList<ItemList> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.list_item, null);
			}
			ItemList o = items.get(position);
			if (o != null) {
				ImageView image = (ImageView) view.findViewById(R.id.image);
				TextView txtPrice = (TextView) view.findViewById(R.id.txtPrice);
				TextView txtPlace = (TextView) view.findViewById(R.id.txtPlace);
				TextView txtLongitude = (TextView) view
						.findViewById(R.id.txtLongitude);
				TextView txtLatitude = (TextView) view
						.findViewById(R.id.txtLatitude);
				TextView txtDate = (TextView) view.findViewById(R.id.txtDate);
				TextView txtFile = (TextView) view.findViewById(R.id.txtFile);

				txtFile.setText(o.getImagePath());

				DecimalFormat df = new DecimalFormat("###,##0.00");
				txtPrice.setText(df.format(o.getPrice()) + " RSD");

				txtPlace.setText(o.getPlace());

				txtLongitude.setText(o.getLongitude());
				txtLatitude.setText(o.getLatitude());

				txtDate.setText(o.getDate());

				Bitmap bitmap = BitmapFactory.decodeFile(o.getImagePath());
				image.setImageBitmap(bitmap);

				// ByteArrayInputStream imageStream = new ByteArrayInputStream
				// (o.getSlika());
				// Bitmap theImage = BitmapFactory.decodeStream(imageStream);
				// img.setImageBitmap(theImage);
			}
			return view;
		}
	}
}
